Page({
  data: {
    frontImage: '',
    backImage: '',
    formState: {
      // 身份证
      card_id: '',
      // 人像面
      id_card_front: '',
      // 国徽面
      id_card_back: '',
      // 户籍性质
      household_nature: '',
      // 通信地址
      address: '',
      // 手机号
      phone: '',
      // 姓名
      name: '',
      // 银行卡号
      bank_account: '',
      // 开户行
      bank_branch: '',
      // 社保基数
      insurance_base: '',
      // 审核状态
      status: undefined
    },
    householdNatureOptions: [],
    householdNatureIndex: undefined,
    isFormValid: false
  },

  onLoad() {
    this.checkFormValidity();
    this.getState()
    this.getTerm()
  },

  onAddressChange(e) {
    this.setData({
      'formState.address': e.detail.value
    });
    this.checkFormValidity();
  },

  onPhoneChange(e) {
    this.setData({
      'formState.phone': e.detail.value
    });
    this.checkFormValidity();
  },

  onNameChange(e) {
    this.setData({
      'formState.name': e.detail.value
    });
    this.checkFormValidity();
  },

  onOpenIdChange(e) {
    this.setData({
      'formState.card_id': e.detail.value
    });
    this.checkFormValidity();
  },

  onBankBranchChange(e) {
    this.setData({
      'formState.bank_branch': e.detail.value
    });
    this.checkFormValidity();
  },

  onBankAccountChange(e) {
    this.setData({
      'formState.bank_account': e.detail.value
    });
    this.checkFormValidity();
  },

  onInsuranceBaseChange(e) {
    this.setData({
      'formState.insurance_base': e.detail.value
    });
    this.checkFormValidity();
  },

  onHouseholdNatureChange(e) {
    const selectedValue = this.data.householdNatureOptions[e.detail.value];
    this.setData({
      'formState.household_nature': selectedValue.name,
      'householdNatureIndex': e.detail.value
    });
    this.checkFormValidity();
  },

  // 添加水印函数
  addWatermark(tempFilePath, type) {
    return new Promise((resolve, reject) => {
      // 获取图片信息以确定画布大小
      wx.getImageInfo({
        src: tempFilePath,
        success(imageInfo) {
          // 创建与原图相同尺寸的画布
          const canvasWidth = imageInfo.width
          const canvasHeight = imageInfo.height
          // 设置画布大小
          const query = wx.createSelectorQuery()
          query
            .select("#watermarkCanvas")
            .fields({
              node: true,
              size: true
            })
            .exec((res) => {
              const canvas = res[0].node
              const ctx = canvas.getContext("2d")
              // 设置画布尺寸
              canvas.width = canvasWidth
              canvas.height = canvasHeight
              // 创建图片对象
              const img = canvas.createImage()
              img.onload = () => {
                // 绘制原始图片
                ctx.drawImage(img, 0, 0, canvasWidth, canvasHeight)
                // 添加水印
                const watermarkText = "仅限办理社保使用"
                const watermarkFont = "20px sans-serif"
                const watermarkColor = "rgba(255, 255, 255, 0.5)"
                const watermarkRotate = (-20 * Math.PI) / 180
                const watermarkGapX = 300
                const watermarkGapY = 250
                ctx.font = watermarkFont
                ctx.fillStyle = watermarkColor
                ctx.textAlign = "center"
                // 绘制重复水印
                for (let x = 0; x < canvasWidth; x += watermarkGapX) {
                  for (let y = 0; y < canvasHeight; y += watermarkGapY) {
                    ctx.save()
                    ctx.translate(x + watermarkGapX / 2, y + watermarkGapY / 2)
                    ctx.rotate(watermarkRotate)
                    ctx.fillText(watermarkText, 0, 0)
                    ctx.restore()
                  }
                }
                // 将画布内容转为临时文件
                wx.canvasToTempFilePath({
                  canvas: canvas,
                  success(res) {
                    const watermarkedFilePath = res.tempFilePath
                    resolve(watermarkedFilePath)
                  },
                  fail(err) {
                    reject(err)
                  },
                })
              }
              img.src = tempFilePath
              img.onerror = (err) => {
                reject(err)
              }
            })
        },
        fail(err) {
          reject(err)
        },
      })
    })
  },

  // 修改身份证正面上传函数，先上传原件再上传水印版本
  openCamera(e) {
    const type = e.currentTarget.dataset.type
    const that = this

    wx.chooseImage({
      count: 1,
      sizeType: ["original", "compressed"],
      sourceType: ["camera", "album"],
      success(res) {
        const tempFilePath = res.tempFilePaths[0]
        
        // 先显示原始图片
        that.setData({
          [`${type}Image`]: tempFilePath,
        })

        // 第一步：先上传原件（不加水印）
        that.uploadImage(tempFilePath, type, 'id_card_front_real')
          .then(() => {
            console.log('原件上传成功')
            // 第二步：添加水印
            return that.addWatermark(tempFilePath, type)
          })
          .then((watermarkedFilePath) => {
            // 更新显示为水印图片
            that.setData({
              [`${type}Image`]: watermarkedFilePath,
            })
            // 第三步：上传水印后的图片
            return that.uploadImage(watermarkedFilePath, type, 'id_card_front')
          })
          .catch((err) => {
            console.error('处理图片失败:', err)
            wx.showToast({
              title: "处理图片失败",
              icon: "none",
            })
          })
      },
    })
  },

  // 修改身份证国徽面上传函数，先上传原件再上传水印版本
  openCamera1(e) {
    const type = e.currentTarget.dataset.type
    const that = this

    wx.chooseImage({
      count: 1,
      sizeType: ["original", "compressed"],
      sourceType: ["camera", "album"],
      success(res) {
        const tempFilePath = res.tempFilePaths[0]
        
        // 先显示原始图片
        that.setData({
          [`${type}Image`]: tempFilePath,
        })

        // 第一步：先上传原件（不加水印）
        that.uploadImage(tempFilePath, type, 'id_card_back_real')
          .then(() => {
            console.log('原件上传成功')
            // 第二步：添加水印
            return that.addWatermark(tempFilePath, type)
          })
          .then((watermarkedFilePath) => {
            // 更新显示为水印图片
            that.setData({
              [`${type}Image`]: watermarkedFilePath,
            })
            // 第三步：上传水印后的图片
            return that.uploadImage(watermarkedFilePath, type, 'id_card_back')
          })
          .catch((err) => {
            console.error('处理图片失败:', err)
            wx.showToast({
              title: "处理图片失败",
              icon: "none",
            })
          })
      },
    })
  },

  // 修改上传图片函数，支持不更新formState的选项
  uploadImage(filePath, type, imageType, updateFormState = true) {
    const that = this;
    const app = getApp();
    const uploadUrl = `${app.globalData.baseUrl}/upload/?image_type=${imageType}`; // 服务器上传接口地址

    wx.showLoading({
      title: "上传中...",
    });

    return new Promise((resolve, reject) => {
      // 使用 wx.uploadFile 上传文件
      wx.uploadFile({
        url: uploadUrl, // 上传接口地址
        filePath: filePath, // 需要上传的文件路径
        name: "file", // 服务器接收文件的字段名
        success(res) {
          wx.hideLoading();
          try {
            const result = JSON.parse(res.data);
            if (result.code === 200) {
              wx.showToast({
                title: "上传成功",
                icon: "success",
              });

              // 只有上传水印版本时才更新表单数据
              if (updateFormState && (imageType === 'id_card_front' || imageType === 'id_card_back')) {
                that.setData({
                  [`formState.${imageType}`]: result.data.file_path,
                });
                that.checkFormValidity();
              }

              resolve(result);
            } else {
              wx.showToast({
                title: result.message || "上传失败",
                icon: "none",
              });
              reject(new Error(result.message || "上传失败"));
            }
          } catch (e) {
            wx.showToast({
              title: "解析响应失败",
              icon: "none",
            });
            reject(e);
          }
        },
        fail(err) {
          wx.hideLoading();
          wx.showToast({
            title: "上传失败",
            icon: "none",
          });
          reject(err);
        },
      });
    });
  },

  checkFormValidity() {
    const {
      formState
    } = this.data;
    const isValid = !!(
      formState.id_card_front &&
      formState.id_card_back &&
      formState.household_nature &&
      formState.address &&
      formState.bank_account &&
      formState.bank_branch &&
      formState.insurance_base &&
      formState.name &&
      formState.phone &&
      formState.card_id
    );
    this.setData({
      isFormValid: isValid
    });
  },

  getTerm: function() {
    const app = getApp();
    const doGetTerm = `${app.globalData.baseUrl}/term`;
    const that = this

    wx.request({
      url: doGetTerm,
      method: 'GET',
      success(res) {
        console.log(res, 'res0-=0-=-=0')
        if (res.data.code == '500') {
          wx.showToast({
            title: res.data.error,
            icon: 'error'
          });
        } else if (res.data.code === 200) {
          that.setData({
            'householdNatureOptions': res.data.data.select.household_nature.select
          })
        }
      }
    });
  },

  getState: function() {
    const storageState = wx.getStorageSync('formState')
    if (storageState) {
      this.setData({
        formState: storageState
      });
      this.checkFormValidity(); // 确保在初始化后重新计算 isFormValid
    }
  },

  // 失去焦点时的验证函数
  validateIdCard() {
    const {
      card_id
    } = this.data.formState;
    if (!card_id) return; // 如果为空，不验证

    const idCardRegex = /^[1-9]\d{5}(18|19|20)?\d{2}((0[1-9])|(10|11|12))(([0-2][0-9])|10|20|30|31)\d{3}(\d|[Xx])$/;
    if (!idCardRegex.test(card_id)) {
      wx.showToast({
        title: '请输入有效的身份证号',
        icon: 'none'
      });
    }
  },

  validatePhone() {
    const {
      phone
    } = this.data.formState;
    if (!phone) return; // 如果为空，不验证

    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phoneRegex.test(phone)) {
      wx.showToast({
        title: '请输入有效的手机号',
        icon: 'none'
      });
    }
  },

  validateName() {
    const {
      name
    } = this.data.formState;
    if (!name) {
      wx.showToast({
        title: '请输入姓名',
        icon: 'none'
      });
    }
  },

  validateAddress() {
    const {
      address
    } = this.data.formState;
    if (!address) {
      wx.showToast({
        title: '请输入通讯地址',
        icon: 'none'
      });
    }
  },

  validateBankBranch() {
    const {
      bank_branch
    } = this.data.formState;
    if (!bank_branch) {
      wx.showToast({
        title: '请输入开户行',
        icon: 'none'
      });
    }
  },

  validateBankAccount() {
    const {
      bank_account
    } = this.data.formState;
    if (!bank_account) return; // 如果为空，不验证

    const bankAccountRegex = /^\d{16,19}$/;
    if (!bankAccountRegex.test(bank_account)) {
      wx.showToast({
        title: '请输入有效的银行卡号',
        icon: 'none'
      });
    }
  },

  validateInsuranceBase() {
    const {
      insurance_base
    } = this.data.formState;
    if (!insurance_base) return; // 如果为空，不验证

    const insuranceBase = Number(insurance_base);
    if (isNaN(insuranceBase)) {
      wx.showToast({
        title: '社保基数必须是数字',
        icon: 'none'
      });
      return;
    }

    if (insuranceBase < 6821 || insuranceBase > 35283) {
      wx.showToast({
        title: '社保基数必须在6821到35283之间',
        icon: 'none'
      });
    }
  },

  handleSubmit() {
    const {
      formState
    } = this.data;

    // 验证社保基数是否在指定范围内
    const insuranceBase = Number(formState.insurance_base);
    if (isNaN(insuranceBase) || insuranceBase < 6821 || insuranceBase > 35283) {
      wx.showToast({
        title: '社保基数必须在6821到35283之间',
        icon: 'none'
      });
      return; // 阻止提交
    }

    const app = getApp();
    const doUpdateUser = `${app.globalData.baseUrl}/update_user/`;
    const openId = wx.getStorageSync('openid')

    this.setData({
      "formState.status": 0,
      "formState.household_nature": this.data.householdNatureIndex
    })

    // 提交表单数据
    wx.request({
      url: doUpdateUser + openId,
      method: 'PUT',
      data: formState,
      success(res) {
        if (res.data.code == '500') {
          wx.showToast({
            title: res.data.error,
            icon: 'error'
          });
        } else if (res.data.code === 200) {
          wx.showToast({
            title: '提交成功',
            icon: 'success'
          });
          setTimeout(() => {
            wx.navigateBack();
          }, 1000);
        } else {
          wx.showToast({
            title: '提交失败',
            icon: 'none'
          });
        }
      },
      fail() {
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  }
});